package monitor

import (
	"net/http"
	"strconv"

	"main/handlers"

	"github.com/gin-gonic/gin"
)

// ProjectHealthCalendar 处理获取告警数据的请求
func AppRunInfo(c *gin.Context) {
	projectIDStr := c.Query("project_id")
	projectID, err := strconv.Atoi(projectIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid project ID"})
		return
	}

	// 构建 SQL 查询
	query := `
		WITH LatestEvents AS (  
			SELECT   
				*,  
				ROW_NUMBER() OVER (PARTITION BY alarm_config_id ORDER BY alarm_event_time DESC) AS rn  
			FROM   
				alarm_event  
		)  
		SELECT
			b.project_id,
			a.app_id,  
			a.app_name,  
			ac1.alarm_event_result AS status_alarm_event_result,  
			ac1.alarm_event_result_status AS status_alarm_event_result_status, 
			ac1.alarm_event_result_time AS status_alarm_event_result_time,
			ac1.alarm_event_alarm_status AS alarm_event_alarm_status,
			ac2.alarm_event_result_status AS cpu_alarm_event_result_status,  
			ac3.alarm_event_result_status AS memory_alarm_event_result_status,  
			ac4.alarm_event_result_status AS disk_alarm_event_result_status,  
			ac5.alarm_event_result_status AS link_alarm_event_result_status  
		FROM   
			app a
		LEFT JOIN 
			hosts b ON a.host_id = b.host_id
		LEFT JOIN   
			LatestEvents ac1 ON a.app_now_status_alarm_config = ac1.alarm_config_id AND ac1.alarm_event_exec_status = 1 AND ac1.rn = 1  	
		LEFT JOIN   
			LatestEvents ac2 ON a.app_cpu_alarm_config = ac2.alarm_config_id AND ac2.rn = 1  
		LEFT JOIN   
			LatestEvents ac3 ON a.app_mem_alarm_config = ac3.alarm_config_id AND ac3.rn = 1  
		LEFT JOIN   
			LatestEvents ac4 ON a.app_disk_alarm_config = ac4.alarm_config_id AND ac4.rn = 1  
		LEFT JOIN   
			LatestEvents ac5 ON a.app_link_alarm_config = ac5.alarm_config_id AND ac5.rn = 1  
		WHERE 
			b.project_id = ?;
	`
	// 执行查询
	results, err := handlers.ExecuteQuery(query, projectID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Error executing query", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, results) // 返回转换后的响应
}
